//
//  ModeViewController.m
//  Player
//
//  Created by howell on 16/3/18.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MujiDubModeViewController.h"
//#import "MBProgressHUD.h"
//#import "WXApi.h"
//#import "YLShareManager.h"
//#import "UIImage+YLExtension.h"
#import "MujiDubHeader.h"
#import "MujiDubProgressView.h"

static const int32_t kMijiDubVideoFramesPerSecond = 5;


@interface MujiDubModeViewController ()


//
//@property (nonatomic, strong) YLShareManager   *shareView;

@property (nonatomic, assign) BOOL   isdealloc;


@end

#define SCREEN_WIDTH    [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT    [[UIScreen mainScreen] bounds].size.height

NSString *MujiTimeStringFromSeconds(NSTimeInterval seconds)
{
    return [NSString stringWithFormat:@"%02ld:%02ld", (long)(seconds/60.0), (long)((NSInteger)seconds)%60];
}


@implementation MujiDubModeViewController

- (id)init
{
    self = [super init];
    if (self)
    {
        _autoPlay                         = NO;
        _isShowChinese = YES;
        _isNoChinese = YES;
        
        _mediaAssetLoader  = [[MujiMediaAssetLoader alloc] init];
        _mediaAssetLoader.dataSource = self;
        _mediaAssetLoader.delegate = self;
        
        self.isdealloc = NO;
        
        //self.mIsSub = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.videoPlayerView = [[MujiVideoPlayerView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_WIDTH/16*9)];
   // self.videoPlayerView = [[ECVideoPlayerView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 230)];
    [self.view addSubview:self.videoPlayerView];
    
    self.loadingBackView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_WIDTH/16*9)];
    self.loadingBackView.image = [UIImage imageNamed:@"videoloading"];
    
    [self.view addSubview:self.loadingBackView];
    
   
    self.loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_WIDTH/16*9)];
    [self.view addSubview:self.loadingView];
    
    self.actiity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _actiity.frame = CGRectMake(self.loadingView.frame.size.width/2, self.loadingView.frame.size.height/2, 30, 30);
    _actiity.center = CGPointMake(self.loadingView.frame.size.width/2, self.loadingView.frame.size.height/2 - 15);
    [self.loadingView addSubview:_actiity];
    [_actiity startAnimating];
    
    self.actiityLabel = [[UILabel alloc] initWithFrame:CGRectMake((self.loadingView.frame.size.width - 100)/2 , CGRectGetMaxY(self.actiity.frame) + 5, 100, 20)];
    //self.timeLabel.textColor = [UIColor whiteColor];
    self.actiityLabel.text = @"加载中";
    self.actiityLabel.textColor = ColorWithRGBA(255, 255, 255, 1.0);
    self.actiityLabel.textAlignment = NSTextAlignmentCenter;
    self.actiityLabel.font = [UIFont systemFontOfSize:12];
    [self.loadingView addSubview:self.actiityLabel];

    int ntimeViewHeight = 39;
    int nActionBtnHeight = 30;
    self.timeView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.videoPlayerView.frame) - ntimeViewHeight, SCREEN_WIDTH, ntimeViewHeight)];
    self.timeView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.33];
    
    
    //self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake( SCREEN_WIDTH - 80 , SCREEN_WIDTH/16*9 - 20, 70, 20)];
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0 , (ntimeViewHeight - 20)/2, 57, 20)];
    //self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textColor = ColorWithRGBA(255, 255, 255, 1.0);
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    
    //self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake( SCREEN_WIDTH - 80 , SCREEN_WIDTH/16*9 - 20, 70, 20)];
    self.totalTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 57 , (ntimeViewHeight - 20)/2, 57, 20)];
    //self.timeLabel.textColor = [UIColor whiteColor];
    self.totalTimeLabel.textColor = ColorWithRGBA(255, 255, 255, 1.0);
    self.totalTimeLabel.textAlignment = NSTextAlignmentCenter;
    self.totalTimeLabel.font = [UIFont systemFontOfSize:12];

    
    UIView *totalTimeView = [[UIView alloc] initWithFrame:CGRectMake(57, (ntimeViewHeight - 2)/2, kScreenWidth - 57 - 57, 2)];
    
    totalTimeView.backgroundColor = ColorWithRGBA(255, 255, 255, 0.5);
    
    
    self.timeProgrssView = [[MujiDubProgressView alloc] initWithFrame:CGRectMake(57, (ntimeViewHeight - 2)/2, kScreenWidth - 57 - 57, 2)];
    
    self.timeProgrssView.progressHeight = 4;
    self.timeProgrssView.trackTintColor = [ColorWithRGBA(255, 255, 255, 1.0) colorWithAlphaComponent:0.5];
    self.timeProgrssView.progressTintColor = ColorWithRGBA(255, 150, 0, 1.0);
    //[self.timeProgrssView setProgress:0.3];
    
    self.subTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, CGRectGetMaxY(self.videoPlayerView.frame) - ntimeViewHeight + (ntimeViewHeight - 30)/2, kScreenWidth - 60 - 60, 30)];
    self.subTitleLabel.textAlignment = NSTextAlignmentCenter;
    self.subTitleLabel.font = [UIFont systemFontOfSize:11];
    self.subTitleLabel.numberOfLines = 0;
    self.subTitleLabel.textColor = [UIColor whiteColor];
    self.subTitleLabel.hidden = YES;
    
    
    [self.timeView addSubview:self.timeLabel];
    //[self.timeView addSubview:totalTimeView];
    [self.timeView addSubview:self.timeProgrssView];
    [self.timeView addSubview:self.totalTimeLabel];
    
    [self.view addSubview:self.subTitleLabel];
    [self.view addSubview:self.timeView];
    
    [self.view addSubview:self.subTitleLabel];
    
    self.backBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, 20 + 6, 39, 39)];
    //self.backBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.backBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_back_white"] forState:UIControlStateNormal];
    [self.backBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_back_white"] forState:UIControlStateHighlighted];
    [self.backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.shareBtn = [[UIButton alloc] initWithFrame:CGRectMake( SCREEN_WIDTH - 64,  0, 64, 64)];
    [self.shareBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [self.shareBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateSelected];
    [self.shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    
    //[self.videoPlayerView addSubview:self.backBtn];
    //[self.videoPlayerView addSubview:self.timeLabel];
    [self.videoPlayerView addSubview:self.shareBtn];
    
    [self.view addSubview:self.backBtn];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(videoPlayViewTap)];
    [self.videoPlayerView addGestureRecognizer:tap];
 
    self.playButton = [[UIButton alloc] initWithFrame:CGRectMake((self.videoPlayerView.frame.size.width - 70)/2, (self.videoPlayerView.frame.size.height - 70)/2, 70, 70)];
    [self.playButton setImage:[UIImage imageNamed:@"icon_dub_videoPlay_normal"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"icon_dub_videoPlay_selected"] forState:UIControlStateSelected];
    [self.playButton addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.playButton.hidden = YES;
    [self.videoPlayerView addSubview:self.playButton];
   // [self showHUDWithMode:MBProgressHUDModeIndeterminate labelText:@""  animated:YES];
    
    [self addHomeNotify];
    
    
    [self.view bringSubviewToFront:self.backBtn];
    
}

-(void)scriptAction
{
    
}

-(void)switchAction
{
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

-(void)addHomeNotify
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.
//    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)applicationWillResignActive:(NSNotification *)notification

{
   // printf("按理说是触发home按下\n");
    self.playButton.hidden = NO;
    [self.videoPlayerView pause];
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
   // printf("按理说是重新进来后响应\n");
}


-(void)shareAction
{
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:MujiDubUserId];
    if (userId.length == 0) {
        userId = @"0";
    }
}

//-(void)playAction
//{
//    self.playButton.hidden = YES;
//    [self.videoPlayerView play];
//}

- (void)videoPlayViewTap
{
    if (self.videoPlayerView.player)
    {
        if (self.videoPlayerView.player.rate > 0.0)
        {
            // Video is playing, so pause it (Play button will show as soon as video is paused):
            [self.videoPlayerView pause];
            self.playButton.hidden = NO;
        }
        else
        {
            self.playButton.hidden = YES;
            [self.videoPlayerView play];
        }
    }
}
- (void)showHUDWithMode:(NSInteger)mode
                         labelText:(NSString *)labelText
                          animated:(BOOL)animated
{
    //NSLog(@"show");
    
    if(self.indicatorView == nil){
        
       // NSLog(@"show111111111");
        self.indicatorView = [[UIActivityIndicatorView alloc] init];
        self.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        self.indicatorView.backgroundColor = [UIColor whiteColor];
        self.indicatorView.center = self.videoPlayerView.center;
        [self.indicatorView startAnimating];
        
        [self.view addSubview:self.indicatorView];
    }
    self.indicatorView.hidden = NO;
}


- (void)hideAllHUDsAnimated:(BOOL)animated
{
    //NSLog(@"hide111");

    if(self.indicatorView){
        
        //NSLog(@"hide22222222");
        self.indicatorView.hidden = YES;
        [self.indicatorView removeFromSuperview];
        self.indicatorView = nil;
    }
}

-(void) initPlayer
{
    NSURL *assetURL = [NSURL URLWithString:_videoUrl];
    
    //NSLog(@"assetURL------------%@", assetURL);
    [self.mediaAssetLoader loadMediaAsset:assetURL];
    
    self.videoPlayerView.videoFillMode = AVLayerVideoGravityResizeAspectFill;
    self.videoPlayerView.delegate      = self;
    self.videoPlayerView.player        = self.mediaAssetLoader.player;
    
    [self setUpTimeObserverOnPlayer:self.videoPlayerView.player];
}

- (void)setUpTimeObserverOnPlayer:(AVPlayer *)player
{
    [self tearDownTimeObserverOnPlayer:player];
    
    if (player)
    {
        __weak MujiDubModeViewController *weakSelf = self;
        self.timeObserver = [player addPeriodicTimeObserverForInterval:CMTimeMake(1,kMijiDubVideoFramesPerSecond)
                                                                 queue:NULL
                                                            usingBlock:^(CMTime time)
                             {
                                 MujiDubModeViewController *strongSelf = weakSelf;
                                 [strongSelf videoTimeTick:time];
                             }];
    }
}

- (void)tearDownTimeObserverOnPlayer:(AVPlayer *)player
{
    if (self.timeObserver)
    {
        @try
        {
            [player removeTimeObserver:self.timeObserver];
        }
        @catch (NSException *__unused exception) {}
        
        self.timeObserver = nil;
    }
}

- (void)videoTimeTick:(CMTime)time
{
    if (!self.isViewLoaded || !self.view.window )
    {
        // Pause video playback whenever a postroll screen or word study card is showing:
        [self.videoPlayerView pause];
    }
}

- (void)updateTimeLabelWithSeconds:(Float64)seconds totalSeconds:(Float64)totalSeconds
{
    NSString *timeString = [NSString stringWithFormat:@"%@/%@",
                            MujiTimeStringFromSeconds(seconds),
                            MujiTimeStringFromSeconds(totalSeconds)];
   // self.timeLabel.text  = timeString;
}

#pragma mark -
#pragma mark MujiMediaAssetLoaderDelegate

- (void)mediaAssetLoader:(MujiMediaAssetLoader *)loader
completedDownloadOfMediaLoadRequest:(MujiMediaLoadRequest *)mediaLoadRequest
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
}

- (void)mediaAssetLoader:(MujiMediaAssetLoader *)loader
  failedLoadingWithError:(NSError *)error
{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
}

-(void)startplayFromLast
{
    
    self.duration = [NSString stringWithFormat:@"%.0f", self.mediaAssetLoader.duration];
    //NSLog(@" self.mediaAssetLoader.duration  %f", self.mediaAssetLoader.duration);
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"kPlayerPlay" object:nil];
    NSLog(@"---------------- startplay ----------------");
}

- (void)mediaAssetLoader:(MujiMediaAssetLoader *)loader
                  player:(AVPlayer *)player
            statusChange:(NSDictionary *)statusChange
{
    printf("player.status--------%ld\n", (long)player.status);
    
    if (player.status == AVPlayerStatusReadyToPlay )
    {
        self.loadingBackView.hidden = YES;
        //        DDLogInfo(@"Player signaled that it is ready to play!");
        if (self.videoPlayerView.player != player)
        {
            self.videoPlayerView.player = player;
        }
        
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
       // cueStart    = 0.001 * dialogLine.cueStart.floatValue;
        CMTime time = CMTimeMake(0, 1.0);
        [self.videoPlayerView.player.currentItem cancelPendingSeeks];
        [self.videoPlayerView seekToTime:time];
        
        //[self.videoPlayerView play];
        [self startplayFromLast];
        
    }
}

- (void)mediaAssetLoader:(MujiMediaAssetLoader *)loader
                  player:(AVPlayer *)player
              rateChange:(NSDictionary *)rateChange
{
    if (player.rate > 0.0)
    {
        if (self.videoPlayerView.player != player)
        {
            self.videoPlayerView.player = player;
        }
    }
    else
    {
        //[self onVideoPaused];
    }
}

#pragma mark -
#pragma mark MujiMediaLoadRequestDataSource

- (BOOL)mediaAssetLoader:(MujiMediaAssetLoader *)mediaAssetLoader
hasStartedPlaybackFromFiredTimeout:(NSTimer *)timeout
{
    
    return self.videoPlayerView.isReadyForVisualDisplay;
}

- (void)backAction
{
    
//    [self.navigationController popViewControllerAnimated:YES];

}


- (void)setupDealloc
{
    printf("-------dealloc ---------------");

    self.mediaAssetLoader.delegate = nil;
    self.mediaAssetLoader.dataSource = nil;
    
    [self.videoPlayerView pause];
    [self tearDownTimeObserverOnPlayer:self.videoPlayerView.player];
    self.videoPlayerView.delegate = nil;
    [self.videoPlayerView seekToTime:CMTimeMake(0, 1)];
    //self.videoPlayerView = nil;
    
    self.videoPlayerView.player = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
